/* Laura Doktorova https://github.com/olado/doT */
(function(){function p(b,a,d){return("string"===typeof a?a:a.toString()).replace(b.define||h,function(a,c,e,g){0===c.indexOf("def.")&&(c=c.substring(4));c in d||(":"===e?(b.defineParams&&g.replace(b.defineParams,function(a,b,l){d[c]={arg:b,text:l}}),c in d||(d[c]=g)):(new Function("def","def['"+c+"']="+g))(d));return""}).replace(b.use||h,function(a,c){b.useParams&&(c=c.replace(b.useParams,function(a,b,c,l){if(d[c]&&d[c].arg&&l)return a=(c+":"+l).replace(/'|\\/g,"_"),d.__exp=d.__exp||{},d.__exp[a]=
	d[c].text.replace(new RegExp("(^|[^\\w$])"+d[c].arg+"([^\\w$])","g"),"$1"+l+"$2"),b+"def.__exp['"+a+"']"}));var e=(new Function("def","return "+c))(d);return e?p(b,e,d):e})}function k(b){return b.replace(/\\('|\\)/g,"$1").replace(/[\r\t\n]/g," ")}var f={version:"1.0.3",templateSettings:{evaluate:/\{\{([\s\S]+?(\}?)+)\}\}/g,interpolate:/\{\{=([\s\S]+?)\}\}/g,encode:/\{\{!([\s\S]+?)\}\}/g,use:/\{\{#([\s\S]+?)\}\}/g,useParams:/(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,
	define:/\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,defineParams:/^\s*([\w$]+):([\s\S]+)/,conditional:/\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,iterate:/\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,varname:"it",strip:!0,append:!0,selfcontained:!1,doNotSkipEncoded:!1},template:void 0,compile:void 0},m;f.encodeHTMLSource=function(b){var a={"&":"&#38;","<":"&#60;",">":"&#62;",'"':"&#34;","'":"&#39;","/":"&#47;"},d=b?/[&<>"'\/]/g:/&(?!#?\w+;)|<|>|"|'|\//g;return function(b){return b?
	b.toString().replace(d,function(b){return a[b]||b}):""}};m=function(){return this||(0,eval)("this")}();"undefined"!==typeof module&&module.exports?module.exports=f:"function"===typeof define&&define.amd?define(function(){return f}):m.doT=f;var r={start:"'+(",end:")+'",startencode:"'+encodeHTML("},s={start:"';out+=(",end:");out+='",startencode:"';out+=encodeHTML("},h=/$^/;f.template=function(b,a,d){a=a||f.templateSettings;var n=a.append?r:s,c,e=0,g;b=a.use||a.define?p(a,b,d||{}):b;b=("var out='"+(a.strip?
	b.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g," ").replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,""):b).replace(/'|\\/g,"\\$&").replace(a.interpolate||h,function(b,a){return n.start+k(a)+n.end}).replace(a.encode||h,function(b,a){c=!0;return n.startencode+k(a)+n.end}).replace(a.conditional||h,function(b,a,c){return a?c?"';}else if("+k(c)+"){out+='":"';}else{out+='":c?"';if("+k(c)+"){out+='":"';}out+='"}).replace(a.iterate||h,function(b,a,c,d){if(!a)return"';} } out+='";e+=1;g=d||"i"+e;a=k(a);return"';var arr"+
	e+"="+a+";if(arr"+e+"){var "+c+","+g+"=-1,l"+e+"=arr"+e+".length-1;while("+g+"<l"+e+"){"+c+"=arr"+e+"["+g+"+=1];out+='"}).replace(a.evaluate||h,function(a,b){return"';"+k(b)+"out+='"})+"';return out;").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/(\s|;|\}|^|\{)out\+='';/g,"$1").replace(/\+''/g,"");c&&(a.selfcontained||!m||m._encodeHTML||(m._encodeHTML=f.encodeHTMLSource(a.doNotSkipEncoded)),b="var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : ("+f.encodeHTMLSource.toString()+
	"("+(a.doNotSkipEncoded||"")+"));"+b);try{return new Function(a.varname,b)}catch(q){throw"undefined"!==typeof console&&console.log("Could not create a template function: "+b),q;}};f.compile=function(b,a){return f.template(b,null,a)}})();

(function($){
	var _globalLoading;

	window.juq = {
		showTip: function (type, msg, stayTime, cb) {
			if(stayTime !== 0 && !stayTime){
				stayTime = msg.length*300;
			}
			var el = $.tips({
				content: msg,
				stayTime: stayTime,
				type: type,
				callback: cb || function () {
				}
			});
			if (cb) {
				el.on("tips:hide", cb);
			}
		},
		showTipErr: function (msg, stayTime) {
			juq.showTip('warn', msg, stayTime);
		},
		showTipSuc: function (msg, stayTime) {
			juq.showTip('success', msg, stayTime);
		},
		showTipInfo: function (msg, stayTime) {
			juq.showTip('info', msg, stayTime);
		},
		showLoading: function () {
			_globalLoading = $.loading({content: '加载中...'});
			$('.ui-loading-block.show').removeAttr('style');
		},
		hideLoading: function () {
			_globalLoading && _globalLoading.loading('hide');
		},
		fajax:function(url,p,settings){
			var defaults = {
				type:'get',
				error:function(code,msg){
					juq.hideLoading();
					juq.showTipErr(msg);
				},
				success: function() {},
				complete:function(jqXHR, textStatus){}
			};
			settings = $.extend(defaults, settings);
			$.ajax({
				cache:false,
				url: url,
				type: settings.type,
				data: p,
				dataType: 'json',
				success: function(result) {
					if (result.res > 0) {
						settings.success(result.info,result);
					}
					else{
						settings.error(result.res,result.info, result);
					}
				},
				complete: function(jqXHR, textStatus){
					settings.complete(jqXHR, textStatus);
				},
				error: function(jqXHR, textStatus, errorThrown) {
					settings.error(-1,textStatus);
				}
			});
		},
		fget:function(url,p,success,error){
			juq.fajax(url,p,{type:'get',
				success:success,
				error:error
			});
		},
		fpost:function(url,p,success,error){
			juq.fajax(url,p,{type:'post',
				success:success,
				error:error
			});
		},
		log:function(type, msg){
			$.post('http://p.juqingdata.com/log/index',{info:msg, type:type||'info'})
		}
	};
})(Zepto);


(function($){
	$.extend($.fn,{
		tmpl:function(data){
			return doT.template($(this).html()).apply(null,[data]);
		},
		fpost:function(url,p,success,error){
			var $this = $(this);
			var ov = $this.val();
			var nv = $this.data('ltext');

			if($this.data('loading')){
				return;
			}
			$this.val(nv).data('loading',1);
			juq.showLoading();
			juq.fpost(url,p,function(data, res){
				juq.hideLoading();
				$this.val(ov);
				$this.removeData('loading');
				success && success(data,res);
			},function(){
				juq.hideLoading();
				$this.val(ov);
				$this.removeData('loading');
				error && error(code,msg,res);
			});
		}
	});
})(Zepto);

(function(){
	window.onerror = function(sMessage,sUrl,sLine){
		juq.log('m_js_error', 'sline:'+sLine+'; surl:'+sUrl+'; smsg:'+sMessage);
	};
	window.upload = {
		/*img:null,
		file:null,
		cb:null,
		cbErr:null,
		stime:0,
		params:{},*/
		upImg:function(FILE, img, params, cb, cbErr, notImg, updateProgress){
			var file = FILE;
			var stime = (+new Date());
			juq.log('m_upload_start', 'type:' + file.type + ';name:' + file.name + ';size:' + file.size + ';time:' + stime);
			if(notImg){
				if(file.size>20480000){
					upload.cbErr('上传文件过大', file, stime, cbErr);
					return;
				}
				upload.__upload(file, file, params, cb, cbErr, stime, updateProgress);
			}else {
				upload.__compress(img, file, params, cb, cbErr, stime, null);
			}
		},
		__upload:function(dataImg, file, params, cb, cbErr, stime, updateProgress){
			var data = new FormData();

			if(params['upyunConfig']){
				var bucket = params['upyunConfig']['bucket'];
				var domain = params['upyunConfig']['domain'];
				data.append('policy', params['upyunConfig']['policy']);
				data.append('signature', params['upyunConfig']['signature']);
				data.append('file', dataImg, file.name);

				$.ajax({ url: 'http://v0.api.upyun.com/'+bucket, type: 'POST', data: data, dataType: 'JSON', cache: false, processData: false, contentType: false,
					beforeSend: function (xhr) {
						xhr.upload.onprogress = updateProgress;
					},success:function(data) {
						//console.log(data);
						data = JSON.parse(data);
						upload.cb(domain+data.url, data, file, stime, cb);
					},error:function(xhr){
						try{
							var data = JSON.parse(xhr.response);
							var codeMap = {
								'file type error':'上传的文件格式有误',
								'file too large':'上传的文件过大'
							};
							var msg = codeMap[data.message] ? codeMap[data.message] : data.message;
							upload.cbErr(msg, file, stime, cbErr);
						}catch (e){
							//console.log(arguments);
							upload.cbErr('上传失败'+xhr.response||'', file, stime, cbErr);
						}
					}
				});

			}else{
				for(var i in params){
					data.append(i, params[i]);
				}
				data.append('houseMaps', dataImg, file.name);
				$.ajax({ url: '/rest/svcWx/mdUploadCommon', type: 'POST', data: data, dataType: 'JSON', cache: false, processData: false, contentType: false, success:function(data) {
					data = JSON.parse(data);
					if(data.res>0) {
						upload.cb(data.info.fname, data, file, stime, cb);
					}else{
						upload.cbErr(data.info, file, stime, cbErr);
					}
				},error:function(){
					upload.cbErr('上传失败', file, stime, cbErr);
				}});
			}
		},
		__toBlob:function(dataURI){
			// 解码base64
			var byteString = atob(dataURI.split(',')[1]);
			var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
			// 类型数组
			// console.log(byteString.length)
			var ia = new Uint8Array(byteString.length);
			for (var i = 0; i < byteString.length; i++) {
				ia[i] = byteString.charCodeAt(i);
			}
			try {
				return new Blob([ia], {
					type: mimeString
				});
			}catch(e){
				return null;
				//android 4.0 formdata post blob is empty
				window.BlobBuilder = window.BlobBuilder ||
					window.WebKitBlobBuilder ||
					window.MozBlobBuilder ||
					window.MSBlobBuilder;
				if(e.name == 'TypeError' && window.BlobBuilder){
					try {
						var bb = new BlobBuilder();
						bb.append(ia);
						return bb.getBlob(mimeString);
					}catch (e){alert(e.message+';'+e.name);}
				}
				else if(e.name == "InvalidStateError"){
					return new Blob( [ia], {type : mimeString});
				}
				else{
					juq.showTipErr('暂不支持你的手机上传图片');
				}
			}
		},
		__compress:function(img, file, params, cb, cbErr, stime, updateProgress){
			var fr = new FileReader();
			fr.readAsDataURL(file);
			fr.onload = function(e){
				var oldSrc = img.attr('src');
				img.attr('src', e.target.result);
				img[0].onload = function(){
					img[0].onload = null;
					var imgObj = this;
					var mime_type = this.src.split(',')[0].split(':')[1].split(';')[0];
					var maxWidth = 2000, maxHeight=2000;

					EXIF.getData(imgObj, function(){
						var orientation = EXIF.getTag(this, 'Orientation');
						var _img = document.createElement('img');
						var mpImg = new MegaPixImage(file);

						var p = {
							maxWidth: maxWidth,
							maxHeight: maxHeight
						};
						if(orientation){
							p['orientation'] = orientation;
						}
						mpImg.onrender = function (target) {
							var dataUrl = target.src;
							var dataImg = upload.__toBlob(dataUrl);

							if(!dataImg){
								img.attr('src', oldSrc);
								juq.showTipErr('请在微信中提交理赔订单');
							}else if(dataImg.size>2000000){
								upload.cbErr('文件大小不能大于2M.', file, stime, cbErr);
								img.attr('src', oldSrc);
							}else {
								upload.__upload(dataImg, file, params, cb, cbErr, stime, updateProgress);
							}
						};
						mpImg.render(_img, p);
					});
				}
			}
		},
		cb:function(url, data, file, stime, cb){
			var dtime =(+new Date()) - stime ;
			juq.log('m_upload_suc', 'type:' + file.type + ';name:' + file.name + ';size:' + file.size + ';time:' + dtime + ';url:' + url);
			cb(url, data);
		},
		cbErr:function(msg, file, stime, cbErr){
			var dtime =(+new Date()) - stime ;
			juq.log('m_upload_error', 'type:' + file.type + ';name:' + file.name + ';size:' + file.size + ';time:' + dtime + ';msg:' + msg);
			cbErr(msg);
		}
	};
})();